﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.TextTemplating.VSHost;
using Microsoft.VisualStudio.TextTemplating;
using Microsoft.VisualStudio.Shell;
using System.IO;
using ScaffoldIt.Helpers;

namespace ScaffoldIt
{
    class ScaffoldingEngine : ITextTemplatingCallback
    {
        private List<ScaffoldingError> _errors;

        private VsOutputWriter _writer;

        private ITextTemplating TextTemplates { get; set; }

        private string CurrentTemplate { get; set; }
        
        private ITextTemplatingSessionHost TemplateHost
        {
            get
            {
                return (ITextTemplatingSessionHost)TextTemplates;
            }
        }



        public ScaffoldingEngine(EnvDTE80.DTE2 DTE, VsOutputWriter writer, List<ScaffoldingError> errors)
        {
            _errors = errors;
            _writer = writer;
            TextTemplates = (ITextTemplating)Package.GetGlobalService(typeof(STextTemplating));            
        }

        public void InitTemplateContext(TextTemplatingSession session)
        {
            //session.Clear(); 
            TemplateHost.Session = session;
        }

        public string ApplyTemplate(string templateFile)
        {
            CurrentTemplate = templateFile;
            var templatecontent = string.Empty;
            using (var reader = new StreamReader(templateFile))
            {
                templatecontent = reader.ReadToEnd();
            }
            return TextTemplates.ProcessTemplate(templateFile, templatecontent, this, null);
        }

        public void ErrorCallback(bool warning, string message, int line, int column)
        {
            ScaffoldingError err = new ScaffoldingError()
            {
                TemplateFile = CurrentTemplate,
                Warning = warning,
                Message = message,
                Column = column,
                Line = line
            };
            _errors.Add(err);
            _writer.WriteLine(err.ToString());
        }

        public void SetFileExtension(string extension)
        {

        }

        public void SetOutputEncoding(System.Text.Encoding encoding, bool fromOutputDirective)
        {

        }
    }
}
